package com.example.project10;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.bumptech.glide.Glide;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import de.hdodenhof.circleimageview.CircleImageView;

public class MineFragment extends Fragment {

    private static final String AVATAR_DIR = "avatars";

    private CircleImageView ivAvatar;
    private TextView tvUserEmail;
    private TextView tvCurrentInterest;
    private Button btnSelectInterest;
    private Button btnMyBooks;
    private Button btnLogout;
    private SharedViewModel sharedViewModel;
    private ActivityResultLauncher<Intent> pickImageLauncher;
    private ActivityResultLauncher<String> requestPermissionLauncher;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 初始化权限请求回调
        requestPermissionLauncher = registerForActivityResult(
                new ActivityResultContracts.RequestPermission(),
                isGranted -> {
                    if (isGranted) {
                        // 权限被授予，直接打开相册
                        openGalleryInternal();
                    } else {
                        // 权限被拒绝，给出提示
                        Toast.makeText(getContext(), "需要存储权限才能选择图片", Toast.LENGTH_SHORT).show();
                    }
                }
        );

        // 初始化图片选择器结果回调
        pickImageLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == Activity.RESULT_OK && result.getData() != null) {
                        Uri imageUri = result.getData().getData();
                        if (imageUri != null) {
                            // 立即更新UI
                            Glide.with(this).load(imageUri).into(ivAvatar);
                            // 保存图片到本地
                            saveAvatar(imageUri);
                        }
                    }
                }
        );
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_mine, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        // 初始化视图
        ivAvatar = view.findViewById(R.id.iv_avatar);
        tvUserEmail = view.findViewById(R.id.tv_user_email);
        tvCurrentInterest = view.findViewById(R.id.tv_current_interest);
        btnSelectInterest = view.findViewById(R.id.btn_select_interest);
        btnMyBooks = view.findViewById(R.id.btn_my_books);
        btnLogout = view.findViewById(R.id.btn_logout);

        // 获取 ViewModel 实例
        sharedViewModel = new ViewModelProvider(requireActivity()).get(SharedViewModel.class);

        // 观察并更新 UI
        sharedViewModel.getUserEmail().observe(getViewLifecycleOwner(), email -> {
            tvUserEmail.setText("用户邮箱: " + (email != null ? email : "未登录"));
            if (email != null) {
                loadAvatar(email);
            }
        });

        sharedViewModel.getCurrentInterest().observe(getViewLifecycleOwner(), interest -> {
            tvCurrentInterest.setText("当前兴趣: " + interest);
        });

        // 设置点击事件
        ivAvatar.setOnClickListener(v -> checkPermissionAndOpenGallery());
        btnSelectInterest.setOnClickListener(v -> showInterestDialog());
        btnMyBooks.setOnClickListener(v -> openBookList());
        btnLogout.setOnClickListener(v -> sharedViewModel.logout());
    }

    private void checkPermissionAndOpenGallery() {
        String permission;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            permission = Manifest.permission.READ_MEDIA_IMAGES;
        } else {
            permission = Manifest.permission.READ_EXTERNAL_STORAGE;
        }

        if (ContextCompat.checkSelfPermission(getContext(), permission) == PackageManager.PERMISSION_GRANTED) {
            openGalleryInternal();
        } else if (shouldShowRequestPermissionRationale(permission)) {
            // 向用户解释为什么需要这个权限
            new AlertDialog.Builder(getContext())
                    .setTitle("权限申请")
                    .setMessage("我们需要您的存储权限来选择相册中的图片作为头像。")
                    .setPositiveButton("好的", (dialog, which) -> requestPermissionLauncher.launch(permission))
                    .setNegativeButton("取消", (dialog, which) -> dialog.dismiss())
                    .create()
                    .show();
        } else {
            // 直接请求权限
            requestPermissionLauncher.launch(permission);
        }
    }

    private void openGalleryInternal() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        pickImageLauncher.launch(intent);
    }

    private void loadAvatar(String userEmail) {
        File avatarDir = new File(getContext().getFilesDir(), AVATAR_DIR);
        File avatarFile = new File(avatarDir, userEmail + ".jpg");

        if (avatarFile.exists()) {
            Glide.with(this)
                    .load(avatarFile)
                    .into(ivAvatar);
        } else {
            // 如果没有保存的头像，可以设置一个默认头像
            Glide.with(this)
                    .load(R.drawable.ic_launcher_foreground) // 使用启动器图标作为默认头像
                    .into(ivAvatar);
        }
    }

    private void saveAvatar(Uri imageUri) {
        String userEmail = sharedViewModel.getUserEmail().getValue();
        if (userEmail == null || userEmail.isEmpty()) {
            Toast.makeText(getContext(), "无法保存头像，用户未登录", Toast.LENGTH_SHORT).show();
            return;
        }

        File avatarDir = new File(getContext().getFilesDir(), AVATAR_DIR);
        if (!avatarDir.exists()) {
            avatarDir.mkdirs();
        }

        File avatarFile = new File(avatarDir, userEmail + ".jpg");

        // 删除旧头像，符合“最小存储”原则
        if (avatarFile.exists()) {
            avatarFile.delete();
        }

        try (InputStream inputStream = getContext().getContentResolver().openInputStream(imageUri);
             OutputStream outputStream = new FileOutputStream(avatarFile)) {

            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, length);
            }
            Toast.makeText(getContext(), "头像更新成功", Toast.LENGTH_SHORT).show();

        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getContext(), "头像保存失败", Toast.LENGTH_SHORT).show();
        }
    }

    private void showInterestDialog() {
        // 兴趣列表
        final String[] interests = {"编程", "音乐", "旅行", "美食", "健身"};

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("请选择您的兴趣");
        builder.setItems(interests, (dialog, which) -> {
            // "which" 参数是用户点击的选项的索引
            String selectedInterest = interests[which];
            // 更新 ViewModel 中的数据
            sharedViewModel.setCurrentInterest(selectedInterest);
        });
        builder.show();
    }

    private void openBookList() {
        String userEmail = sharedViewModel.getUserEmail().getValue();
        if (userEmail != null) {
            Intent intent = new Intent(getActivity(), BookListActivity.class);
            intent.putExtra("user_email", userEmail);
            startActivity(intent);
        }
    }
}